package kr.hkit.androidcomplete01.ch17;

import kr.hkit.androidcomplete01.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class LongTime5 extends Activity {
	int mValue;
	TextView mText;
	ProgressDialog mProgress;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_longtime);
		
		mText = (TextView) findViewById(R.id.text);
	}
	
	public void mOnClick(View v){
		new AccumulateTast().execute(100);
	}
	
	class AccumulateTast extends AsyncTask<Integer, Integer, Void>{
		@Override
		protected void onPreExecute() {
			mProgress = new ProgressDialog(LongTime5.this);
			mProgress.setTitle("Updating...");
			mProgress.setMessage("downloading....");
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setCancelable(true);
			mProgress.setProgress(mValue);
			mProgress.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					cancel(true);
				}
			});
			mProgress.show();
		}

		@Override
		protected Void doInBackground(Integer... params) {
			while(!isCancelled()){
				mValue++;
				if(mValue<params[0]+1){
					publishProgress(mValue);
				}else{
					break;
				}
				try{
					Thread.sleep(100);
				}catch(InterruptedException e){}
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			mText.setText(values[0] + "");
			mProgress.setProgress(mValue);
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			mProgress.dismiss();
			mValue=0;
		}


		@Override
		protected void onCancelled() {
			super.onCancelled();
			mProgress.dismiss();
		}
		
	}
}
